import { API_URLS } from '../config'
import { UserPageParams, User} from '../types/user'
import { Response, PageData, defaultPageData} from '../types/common'
import { request } from '../utils/request'
import { ElMessage } from 'element-plus'

export const getUserPage = async (params: UserPageParams): Promise<PageData<User>> => {
  const response: Response<PageData<User>> = await request(API_URLS.USER_PAGE, {
    method: 'POST',
    body: JSON.stringify(params)
  })

  if (response.code === 200) {
    return response.data
  }

  return defaultPageData
}

export const deleteUser = async (id: number | null): Promise<boolean> => {
  if (!id) return false
  const response:Response<boolean> = await request(`${API_URLS.USER_BASE}/${id}`, {
    method: 'DELETE',
  })

  if (response.code === 200) {
    ElMessage.success('删除成功')
    return true
  } else {
    return false
  }
  
} 

export const addOrUpdateUser = async (params: User, isAdd: boolean): Promise<boolean> => {
  const response:Response<boolean> = await request(`${API_URLS.USER_BASE}`, {
    method: isAdd ? 'POST' : 'PUT',
    body: JSON.stringify(params)
  })

  if (response.code === 200) {
    ElMessage.success(isAdd ? '添加成功' : '编辑成功')
    return true
  } else {
    return false
  }
} 